<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 讲师 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-button type="primary" class="handle-del mr10" @click="addDialog">新增讲师</el-button>
            <div class="handle-box">
                <el-input v-model="query.keyword" placeholder="输入讲师姓名" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table :data="tableData" class="table" ref="multipleTable" header-cell-class-name="table-header">
                <el-table-column label="讲师图片" width="100">
                    <template slot-scope="scope">
                        <img :src="scope.row.cover" @error="tabErrorPicture(scope.row.id)" alt="" class="info-image" />
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="讲师姓名"></el-table-column>
                <el-table-column prop="description" label="讲师描述"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        {{ scope.row.status == 0 ? '禁用' : '启用' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="240" align="center" fixed="right">
                    <template slot-scope="scope">
                        <el-button @click="edit(scope.row)" type="success" size="mini">编辑</el-button>
                        <el-button @click="disable(scope.row.id, scope.row.status)" type="warning" size="mini">{{ scope.row.status == 0 ? '启用' : '禁用' }}</el-button>
                        <el-button @click="deleteRow(scope.row.id, scope.$index)" type="danger" size="mini">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background layout="total, prev, pager, next" :current-page="query.page"
                    :page-size="query.rows" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
            </div>
        </div>
        <!-- 新增讲师弹出框 -->
        <el-dialog title="新增/编辑 讲师" @close="cancel" :visible.sync="showDialog" width="50%">
            <el-form ref="form" :rules="rules" :model="form" label-width="125px">
                <el-form-item label="讲师姓名" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="讲师描述" prop="description">
                    <el-input type="textarea" :rows="2" v-model="form.description"></el-input>
                </el-form-item>
                <el-form-item label="讲师图片">
                    <div class="avatar-uploader" @click="showUploadImage('teacherfm')">
						<img v-if="form.cover" :src="form.cover" class="avatar" height="200px">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</div>
                    <div slot="tip" class="el-upload__tip">建议尺寸：400*400px。</div>
                </el-form-item>
                <el-form-item label="选择用户">
                    <el-button @click="chooseUser" type="primary" size="small">选择用户</el-button>
                    <div class="choose_user" v-if="form.nickname">
                        <div class="user_avatar">
                            <img :src="form.avatar" alt="" />
                        </div>
                        <div class="user_nickname">昵称:{{ form.nickname }}</div>
                        <div class="user_nickname">手机号:{{ form.phone }}</div>
                    </div>
					
                </el-form-item>
				
				<!-- <qriously :value="item.domainurl" :size="100" class="shop-img"/> -->
				
				<el-form-item label="扫码成为老师">
					<qriously :value="qrvalue" :size="100" />
				</el-form-item>

				
                <el-form-item label="完整内容">
                    <quill-editor v-model="form.content" :options="editorOption" ref="myQuillEditor"></quill-editor>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input v-model="form.sort"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="save('form')">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 选择用户弹框 -->
        <el-dialog width="46%" title="选择用户" @close="exit" :visible.sync="innerVisible" append-to-body>
            <div class="choice-box">
                <el-input v-model="userQuery.keyword" placeholder="输入用户手机号" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearchCourse">搜索</el-button>
            </div>
            <div class="course_list" style="height: 300px">
                <div @click="choiceCourse(item.uid, item.avatar, item.nickname,item.phone)" class="course_list_item"
                    v-for="(item, index) in userList" :key="index">
                    <div class="avatar">
                        <img :src="item.avatar" alt="" />
                    </div>
                    <div class="nickname">昵称:{{ item.nickname }}</div>
                    <div class="nickname">手机号:{{item.phone}}</div>
                </div>
            </div>
            <div class="innerPagination">
                <el-pagination background layout="total, prev, pager, next" :current-page="userQuery.page"
                    :page-size="userQuery.rows" :total="userPageTotal" @current-change="userHandlePageChange">
                </el-pagination>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="exit">关 闭</el-button>
            </span>
        </el-dialog>
        <uploadimage ref="uploadimagecom" v-on:childByImageValue="childByImageValue"></uploadimage>
    </div>
</template>

<script>
// 自定义工具栏配置
const toolbarOptions = [
	["bold", "italic", "underline", "strike"], // toggled buttons
	["blockquote", "code-block"],

	[{ header: 1 }, { header: 2 }], // custom button values
	[{ list: "ordered" }, { list: "bullet" }],
	[{ script: "sub" }, { script: "super" }], // superscript/subscript
	[{ indent: "-1" }, { indent: "+1" }], // outdent/indent
	[{ direction: "rtl" }], // text direction

	[{ size: ["small", false, "large", "huge"] }], // custom dropdown
	[{ header: [1, 2, 3, 4, 5, 6, false] }],

	[{ color: [] }, { background: [] }], // dropdown with defaults from theme
	[{ font: [] }],
	[{ align: [] }],
	["link", "image", "video"], // 对于图片上传这是重点
	["clean"], // remove formatting button
];
import uploadimage from '@/components/common/uploadimage.vue';
import { lecturerListData, userListData, addLecturerData, delLecturerData } from '../../api/index';
export default {
    // name: 'lecturer',
    components: {
		uploadimage
	},
    data() {
        return {
			// qrvalue:"https://api.nashicike.top/admin/teachernew/directAddTeacher?domainname=",
			qrvalue:"https://api.nashicike.top/admin/teachernew/directAddTeacher",
            query: {
                page: localStorage.getItem("lastpage")?localStorage.getItem("lastpage"):1,
                rows: 4,
                keyword: ''
            },
            userQuery: {
                page: 1,
                rows: 9,
                keyword: ''
            },
            imgUrl: 'http://api.xuejing.pro/admin/file/image',
            pictureList: [],
            form: {
                id: '',
                uid: '',
                name: '',
                description: '',
                cover: '',
                avatar: '',
                nickname: '',
                content: '',
                sort: '',
                status: 1
            },
            rules: {
                name: [{ required: true, message: "请输入讲师姓名", trigger: "blur" }],
                uid: [{ required: true, message: "请选择用户", trigger: "bulr" }],
                //description: [{ required: true, message: "请输入讲师描述", trigger: "blur" }]
            },
            tableData: [],
            userList: [],
            showDialog: false,
            innerVisible: false,
            pageTotal: 0,
            userPageTotal: 0,
            // 富文本自定义配置项
			editorOption: {
				modules: {
					toolbar: {
						container: toolbarOptions, // 工具栏
						handlers: {
							// 此处开始改写自带的图片上传
							image: (value) => {
								this.$refs.uploadimagecom.dialogVisible = true;
								this.action = "form_content_image";
							}
						},
					},
					// 调整图片大小
					imageResize: {
						displayStyles: {
							backgroundColor: 'black',
							border: 'none',
							color: 'white'
						},
						modules: ['Resize', 'DisplaySize', 'Toolbar']
					}
				},
			},
            errorProduct: require('@/assets/img/noProduct.jpg'), 
        };
    },
    created() {
        this.getData();
    },
    methods: {
        tabErrorPicture(id){    // 表格图文封面默认展示图
            let i = this.tableData.findIndex(v => v.id == id);
			this.tableData[i].cover = this.errorProduct;
        },
        getData() {
            lecturerListData(this.query).then((res) => {
                console.log(res);
                this.tableData = res.data.list;
                this.pageTotal = res.data.count;
            });
        },
        // 搜索
        handleSearch() {
            this.$set(this.query);
            this.getData();
        },
        handleSearchCourse() {
            this.chooseUser();
        },
        // 分页
        handlePageChange(val) {
            this.$set(this.query, 'page', val);
            localStorage.setItem('lastpage',this.query.page);
            this.getData();
        },
        userHandlePageChange(val) {
            this.$set(this.userQuery, 'page', val);
            this.chooseUser();
        },
        //新增
        addDialog() {
            this.showDialog = true;
			// this.qrvalue=this.qrvalue+localStorage.getItem("domainname");
			this.qrvalue=this.qrvalue + "?domainname=" + localStorage.getItem("domainname") + "&shopuuid=" + localStorage.getItem("shopuuid");
			
			
			
			// this.qrvalue=this.qrvalue+localStorage.getItem("shopuuid");
			// this.shopuuid=localStorage.getItem("shopuuid")
			
			// console.log(this.qrvalue)
        },
        //编辑
        edit(row) {
            this.showDialog = true;
            this.form.id = row.id;
            this.form = row;
            this.form.avatar = row.member_info.avatar;
            this.form.nickname = row.member_info.nickname;
            this.form.phone=row.member_info.phone;
        },
        //禁用
        disable(id, status) {
            this.$confirm(`确定${status == 0 ? '启用' : '禁用'}吗！`, '提示', {
                type: 'warning'
            }).then(() => {
                addLecturerData({ id: id, status: status == 0 ? 1 : 0 }).then((res) => {
                    if (res.code == 1) {
                        this.$message.success('操作成功');
                        this.getData();
                    }
                });
            });
        },
        //删除
        deleteRow(id, index) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                delLecturerData({ id: id }).then((res) => {
                    if (res.code == 1) {
                        this.$message.success('删除成功');
                        this.tableData.splice(index, 1);
                        this.getData();
                    }
                });
            });
        },
        chooseUser() {
            this.innerVisible = true;
            userListData(this.userQuery).then((res) => {
                this.userList = res.data.list;
                this.userPageTotal = res.data.count;
            });
        },
        choiceCourse(uid, avatar, nickname,phone) {
            addLecturerData({ check_type: 1, id: this.form.id, uid: uid }).then((res) => {
                if (res.code == 1) {
                    this.innerVisible = false;
                    this.form.uid = uid;
                    this.form.avatar = avatar;
                    this.form.nickname = nickname;
                    this.form.phone=phone;
                } else {
                    this.$message.error('该用户已绑定讲师');
                }
            });
        },
        exit() {
            this.userQuery.page = 1;
            this.userQuery.keyword = '';
            this.innerVisible = false;
        },
        //取消
        cancel() {
            this.form = {};
            this.pictureList = [];
            this.showDialog = false;
        },
        //确定
        save(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    addLecturerData(this.form).then((res) => {
                        if (res.code == 1) {
                            this.showDialog = false;
                            this.$message.success('操作成功');
                            this.getData();
                        }
                    });
                }else{
                    return false
                }
            })

        },
        showUploadImage(action) { //显示上传组件
			this.$refs.uploadimagecom.dialogVisible = true;
			this.action = action;
		},
        //确认按钮传值过来并赋值到form表单上
		childByImageValue: function (childValue) {
			if (this.action == "teacherfm") {
				this.form.cover = childValue;
			}  else if (this.action == "form_content_image") {
				let quill = this.$refs.myQuillEditor.quill;
				// 获取光标所在位置
				let length = quill.getSelection().index;
				// 插入图片，res为服务器返回的图片链接地址
				quill.insertEmbed(length, "image", childValue);
				quill.setSelection(length + 1);
			}
		}
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
    float: right;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.mr10 {
    margin-right: 10px;
}

.info-image {
    width: 80px;
    border-radius: 4px;
}

.user_avatar {
    float: left;
    width: 50px;
    height: 50px;
}

.user_avatar img {
    width: 100%;
    border-radius: 50%;
    overflow: hidden;
}

.user_nickname {
    margin-left: 60px;
    line-height: 50px;
}

.choice-box {
    text-align: center;
    margin-bottom: 20px;
}

.course_list_item {
    float: left;
    width: 220px;
    margin: 10px;
    padding: 5px;
    border: 1px solid #eee;
    cursor: pointer;
    height: 62px;
}

.course_list_item .avatar {
    float: left;
    width: 50px;
    height: 50px;
}

.course_list_item .avatar img {
    width: 100%;
    border-radius: 50%;
}

.course_list_item .nickname {
    margin-left: 60px;
    line-height: 28px;
}
</style>

<style>
.ql-container {
    height: 200px;
}

.avatar-uploader {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	width: 375px !important;
	text-align: center;
}

.avatar-uploader:hover {
	border-color: #409EFF;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
}

.avatar {
	width: 100%;
	display: block;
}
</style>

